import axios from 'axios'
import pinia from '../utils/pinia'
import { ElMessage, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import router from '../router/index'
import baseurl from './env'
import { useStore } from '../store/index'

const http = axios.create()
const Cancel = axios.CancelToken
let httpPending = [] as any

function removeHttpPending(config: any) {
    httpPending.map((item: any, index: any, arr: any) => {
        if (item.u === config.url + '&' + config.method) {
            console.warn(`${config.url}: 短时间内重复请求`)
            item.f()
            arr.splice(index, 1)
        }
        return config
    })
}

function clearHttpPending() {
    httpPending = []
}

const store = useStore(pinia)
// const router = useRouter()
export const request = axios.create({
    baseURL: baseurl,
    timeout: 50000,
})
// 添加请求拦截器
// loading加载

let loading: any
// console.log(request, 'request')
//开启loading
function startLoading() {
    loading = ElLoading.service({
        lock: true,
        text: '',
        background: 'rgba(0,0,0,0.5)',
        customClass: 'el-custom-loading',
    })
}
// 关闭loading
function endLoading() {
    loading.close()
}

const message = (message: string, type: any) => {
    ElMessage({
        message: message,
        type: type,
    })
}
request.interceptors.request.use(
    function (config) {
        if (!config?.noCancel) {
            // removeHttpPending(config)
            // config.cancelToken = new Cancel(c => {
            //     httpPending.push({
            //         u: config.url + '&' + config.method,
            //         f: c
            //     })
            // })
        }
        // console.log(config.url);
        if (sessionStorage.token) {
            //判断token是否存在
            config.headers.Authorization =
                'Bearer ' + sessionStorage.getItem('token') //将token设置成请求头
        }
        setTimeout(() => {
            store.addloadingcount()
            if (store.loadingCount <= 0) {
                return
            }
            if (!config?.noLoading) {
                startLoading()
                store.openloading()
            }
        }, 1000)
        // 在发送请求之前做些什么
        return config
    },
    function (error) {
        // 对请求错误做些什么
        return Promise.reject(error)
    }
)

// 添加响应拦截器
request.interceptors.response.use(
    function (response: any) {
        console.log(store.loadingCount, 'jsgughshuyj')

        clearHttpPending()
        // 关闭loading加载
        setTimeout(() => {
            store.subtractloadingcount()
            if (store.loadingCount === 0) {
                store.closeloading()
                endLoading()
            }
        }, 300)
        // message('请求成功', 'success')
        // 错误码判断
        let data = {}
        console.log('response', response.data.code)
        switch (response.data.code) {
            case 401:
                // 退出(清除token)
                // message(response.data.msg || '用户信息过期请重新登录', 'error')
                // sessionStorage.removeItem('token')
                sessionStorage.clear()
                console.log(router)
                router.push('/login')
                return Promise.reject(response.data)
            case 404:
                message('网络请求错误，请稍后重试或联系管理员！', 'error')
                return Promise.reject(response.data)
            case 200:
                if (response.data.data || response.data.data === 0) {
                    data = response.data.data
                } else {
                    data = response.data
                }
                return data
            default:
                if (
                    response.headers['content-type'] ===
                    'application/octet-stream'
                ) {
                    let filename = response.headers['content-disposition']
                    filename = filename.replace(/attachment;filename/, '')
                    store.setFileName(decodeURIComponent(filename))
                    return response.data
                } else {
                    message(
                        response.data.msg ||
                            '网络请求错误，请稍后重试或联系管理员！',
                        'error'
                    )
                    return Promise.reject(response.data)
                }
        }
        // 对响应数据做点什么
        return response
    },
    function (error) {
        setTimeout(() => {
            store.subtractloadingcount()
            if (store.loadingCount <= 0) {
                store.closeloading()
                endLoading()
            }
        }, 300)
        if (error.code !== 'ERR_CANCELED') {
            message(
                error.msg || '网络请求错误，请稍后重试或联系管理员！',
                'error'
            )
        }
        // 对响应错误做点什么
        return Promise.reject(error)
    }
)
export default request
